using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web;
using System.Diagnostics;
using System.Configuration;
using System.Windows.Forms;

namespace MeetCommon.Service
{

	[Obsolete("This class is no longer used. This is the old server connector used while the MVE server was implemented using non-microsoft technologies. Use the new MeetServerConnector instead.", true)]
	public class MeetServerConnector_old
	{
		private const string STR_DEFAULT_SERVER_ROOT = "http://meet.remixjapan.net/index.php";
		private string strServerRoot = string.Empty;
		private int idUser;

		public MeetServerConnector_old()
		{
			// App.configから読み込む
			strServerRoot = ConfigurationSettings.AppSettings["ServiceEntryPoint"];
			if (string.IsNullOrEmpty(strServerRoot))
				strServerRoot = STR_DEFAULT_SERVER_ROOT;
		}

		public MeetServerConnector_old(string serverRoot)
		{
			strServerRoot = serverRoot;
		}

		#region Public Members
		public bool Logon(string logonId, string password)
		{
			this.idUser = 1;
			return true;

			List<string> lstParams = new List<string>();
			lstParams.Add("login_id=" + logonId);
			lstParams.Add("password=" + password);

			XmlDocument xmlResult = ExecuteCommand("/auth", lstParams.ToArray());
			if (xmlResult == null)
				return false;
			XmlNode node = xmlResult.DocumentElement.SelectSingleNode("/response/status");
			if (node != null && node.InnerText == "0")
			{
				XmlNode nodeUserID = xmlResult.DocumentElement.SelectSingleNode("/response/userid");
				if (nodeUserID != null)
				{
					try
					{
						idUser = Int32.Parse(nodeUserID.InnerText);
					}
					catch (Exception ex)
					{
						Debug.Assert(false, ex.Message);
					}
				}
				return true;
			}
			return false;
		}

		public XmlDocument QueryClips()
		{
			Debug.Assert(this.UserID > 0);
			return ExecuteCommand(string.Format("/mve/clip/{0}", this.UserID), null);
		}

		public XmlDocument ClipSegments(int clip_id)
		{

			return ExecuteCommand(string.Format("/mve/clip/{0}/segments", clip_id), null);
		}


		public XmlDocument Clip(int clip_id)
		{

			return ExecuteCommand(string.Format("/mve/clip/{0}", clip_id), null);
		}

		public XmlDocument ClipBySegmentId(int segment_id)
		{
			return ExecuteCommand(string.Format("/mve/clip/bysegid/{0}", segment_id), null);
		}

		public XmlDocument QuerySegmentByKeyword(string keyword)
		{
			Debug.Assert(this.UserID > 0);

			if (string.IsNullOrEmpty(keyword))
				return null;

			return ExecuteCommand(string.Format("/mve/segments/{0}", HttpUtility.UrlEncode(keyword)), null);
		}

		public XmlDocument QueryKeywords()
		{
			Debug.Assert(this.UserID > 0);

			return ExecuteCommand(string.Format("/mve/mykeywords/{0}", this.UserID), null);
		}


		public bool AddKeywordToSegment(int segment_id, string keyword)
		{
			Debug.Assert(this.UserID > 0);

			if (string.IsNullOrEmpty(keyword))
				return false;

			return ExecuteSimpleCommand(string.Format("/mve/addkeyword/uid/{0}/sid/{1}/keyword/{2}", this.UserID, segment_id, HttpUtility.UrlEncode(keyword)), null);
		}

		public bool DeleteKeyword(int keyword_id)
		{
			Debug.Assert(this.UserID > 0);

			return ExecuteSimpleCommand(string.Format("/mve/delkeyword/{0}/{1}", this.UserID, keyword_id), null);
		}

		public bool AddKeywordToIdeaBasket(string keyword)
		{
			Debug.Assert(this.UserID > 0);

			if (string.IsNullOrEmpty(keyword))
				return false;

			return ExecuteSimpleCommand(string.Format("/mve/addmykeyword/{0}/{1}", this.UserID, HttpUtility.UrlEncode(keyword)), null);
		}

		public bool DeleteIdeaBasketKeyword(string keyword)
		{
			Debug.Assert(this.UserID > 0);

			if (string.IsNullOrEmpty(keyword))
				return false;

			return ExecuteSimpleCommand(string.Format("/mve/delmykeyword/{0}/{1}", this.UserID, HttpUtility.UrlEncode(keyword)), null);
		}

		public XmlDocument QueryBookmarks()
		{
			return ExecuteCommand(string.Format("/mve/bookmark/{0}", this.UserID), null);
		}

		public bool AddBookmark(int segment_id)
		{
			Debug.Assert(this.UserID > 0);

			return ExecuteSimpleCommand(string.Format("/mve/addbookmark/{0}/{1}", segment_id, this.UserID), null);
		}

		public bool DeleteBookmark(int segment_id)
		{
			Debug.Assert(this.UserID > 0);

			return ExecuteSimpleCommand(string.Format("/mve/delbookmark/{0}/{1}", segment_id, this.UserID), null);
		}

		public XmlDocument GetRelations(int segment_id)
		{
			return ExecuteCommand(string.Format("/mve/relations/{0}", segment_id), null);
		}

		public bool SaveMap(string map)
		{
			List<string> lstParams = new List<string>();
			lstParams.Add("data=" + map);

			XmlDocument xmlResult = ExecuteCommand(string.Format("/mve/savemap/{0}", this.UserID), lstParams.ToArray());
			if (xmlResult == null)
				return false;
			return true;
		}

		public XmlDocument RelatedSegments(int segment_id)
		{
			return ExecuteCommand(string.Format("/mve/rsegments/{0}", segment_id), null);
		}

		public string LoadMap()
		{
			return CallMeetServer(string.Format("/mve/loadmap/{0}", this.UserID), null);
		}

		public int UserID
		{
			get { return idUser; }
			set { idUser = value; }
		}

		#endregion

		#region Private Tools Members

		public bool ExecuteSimpleCommand(string command, string[] parameters)
		{
			XmlDocument xmlResult = ExecuteCommand(command, parameters);
			if (xmlResult == null)
				return false;
			XmlNode node = xmlResult.DocumentElement.SelectSingleNode("/response/status");
			if (node != null && node.InnerText == "0")
				return true;
			else
				return false;
		}
		public XmlDocument ExecuteCommand(string command, string[] parameters)
		{
			string strPostParams = string.Empty;
			if (parameters != null)
			{
				foreach (string parameter in parameters)
				{
					if (strPostParams.Length > 0)
						strPostParams += "&";
					strPostParams += parameter;
				}
			}

			return ExecuteCommand(command, strPostParams, false);
		}

		public XmlDocument ExecuteCommand(string command, string postParam, bool fDummy)
		{
			string strResponse = CallMeetServer(command, postParam);

			if (string.IsNullOrEmpty(strResponse)) return null;
			else if (strResponse == "ERROR")
				throw new MVENetworkOperationException("ERROR received", null);
			else if (!strResponse.StartsWith("<?xml"))
				throw new MVENetworkOperationException("unknown response received", null);
			XmlDocument xmlResponse = new XmlDocument();
			xmlResponse.LoadXml(strResponse);
			return xmlResponse;
		}

		public string CallMeetServer(string command, string postParam)
		{
			string url = string.Format("{0}{1}", strServerRoot, command);
			Trace.WriteLine("call: " + url);

			byte[] btResponse;
			try
			{
				System.Net.WebClient webClient = new System.Net.WebClient();
				webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
				if (!string.IsNullOrEmpty(postParam))
				{
					byte[] btPostData = System.Text.Encoding.UTF8.GetBytes(postParam);
					btResponse = webClient.UploadData(url, "POST", btPostData);
				}
				else
					btResponse = webClient.DownloadData(url);
			}
			catch (System.Net.WebException ex)
			{
                MessageBox.Show("Exception: " + ex.Message);
				return null;
			}

			string strResponse = System.Text.Encoding.UTF8.GetString(btResponse);
#if DEBUG

#endif
			return strResponse;
		}
		#endregion
	}
}
